<?php
namespace Company\Controller;
use Think\Controller;
class OrdertestController extends BaseController {
    public function _initialize()
    {
        parent::_initialize();
        $g=session('company');
		C('erp_dbname',$g['db']);
        $db_name=$g['db'];
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		C('db_config.DB_NAME',C('erp_dbname'));
		//数据库连接基础配置-end
    }

	//添加商品
	public function adds_orderdetail(){
		$param=I('param.','','trim');
		$goods_no=explode(",",$param['goods_no']);
		$goods_name=explode(",",$param['goods_name']);
		$goods_price=explode(",",$param['goods_price']);
		$bar_code=explode(",",$param['bar_code']);
		$old_goodslist=session("goodslist");
		$goodslist=session("goodslist");
		$length=count($goodslist);
		foreach($goods_no as $k=>$v){
			// dump($v);
			$goodslist[$k+$length]['goods_no']=$v;
			$goodslist[$k+$length]['goods_name']=$goods_name[$k];
			$goodslist[$k+$length]['goods_price']=$goods_price[$k];
			$goodslist[$k+$length]['bar_code']=$bar_code[$k];
			foreach($old_goodslist as $ks=>$vs){
				// dump($vs);
				if(in_array($v,$vs)){
					alert_json(0,$v."重复添加");
				}
			}
		}
		session("goodslist",$goodslist);
		alert_json(1,"添加成功");
	}
	//订单详细添加
	public function add_orderdetail(){
        $param=I('param.','','trim');

		$warehouse_code=$param['warehouse_code'];
		$manua_id=$param['manua_id'];
		$goods_no=$param['goods_no'];
		$goods_name=$param['goods_name'];
		$bar_code=$param['bar_code'];
		
		$username=$param['username'];
		// dump($param);
		// die;
		if(!empty($username)){
			$db_name=C('DB_PREFIX_T').$username;
			C('db_config.DB_NAME',$db_name);//当前
			$b=M('Book',C('DB_PREFIX_T'), C('db_config'));
			$b_list=$b->where(array('examined'=>2))->select();
			$manua_id="";
			foreach($b_list as $k=>$v){
				$manua_id.=",".$v['book_no'];
			}
			$manua_id=ltrim($manua_id,",");
		}
		
		if(!empty($warehouse_code)){
			$url_arr['warehouse_code']=$warehouse_code;
		}
		if(!empty($goods_no)){
			$url_arr['goods_no']=$goods_no;
		}
		if(!empty($goods_name)){
			$url_arr['goods_name']=$goods_name;
		}
		if(!empty($bar_code)){
			$url_arr['bar_code']=$bar_code;
		}
		if(!empty($manua_id)){
			$url_arr['manua_id']=$manua_id;
		}

		$data['warehouse_code']=$warehouse_code;
		$data['goods_no']=$goods_no;
		$data['goods_name']=$goods_name;
		$data['bar_code']=$bar_code;
		
		$data['manua_id']=$manua_id;
		
		$p=$param['p'];
		$rows=20;
		if(!empty($p)){
			$url_arr['p']=$p;
		}
		
		$data['page']=$p;
		$data['rows']=$rows;
		$data['sort']='id';
		$data['order']='desc';
		
		$url=C('BASE_CONFIG.warehousebound');
		$return=push($url,$data);
		$list=json_decode($return,true);
		
		$Page       = new \Think\Page($list['total'],$data['rows']);
        $show       = $Page->show();
		
		$goodslist=session("goodslist");
		$this->assign('goodslist',$goodslist);
		$this->assign('page',$show);
		$this->assign('total',$list['total']);
		$this->assign('list',$list['rows']);
		$this->display();
	}
	public function del_orderdetail(){
		$param = I('param.','','trim');
		$id=$param['id'];
		$goodslist=session("goodslist");
		unset($goodslist[$id-1]);
		$goodslist=array_values($goodslist);
		session("goodslist",$goodslist);
        echo "y";
	}
	
	//导出订单
	public function excel_export(){
		$api_url="http://www.t-cang.com/oms/index.php/Api/ErpApi/count_excel";//接口地址
		
		$u=M('user');
		$param=I('param.','','trim');
		$username=session('company.username');
		
		$excel=$param['excel'];
		$order_excel=$param['order_excel'];
		
		$u_info=$u->where(array('username'=>$username))->find();
		
		!empty($param['start_time'])?$start_time=$param['start_time']:$start_time=date('Y-m-d',time());
		!empty($param['end_time'])?$end_time=$param['end_time']:$end_time=date('Y-m-d',time()+3600*24);
		
		$push_data['customer']['user_code']=$u_info['user_code'];
		$push_data['customer']['user_key']=$u_info['user_key'];
		
		$page=$param['page'];
		if(empty($page)){
			$page=1;
		}
		if($page=="undefined"){
			$page=1;
		}
		$push_data['data']['start_time']=$start_time;
		$push_data['data']['end_time']=$end_time;
		$push_data['data']['p']=$page;
		$push_data['data']['page_size']=15000;
		if($order_excel!=1){
			$push_data['data']['download']=1;
		}
		
		$res=push($api_url,$push_data);
		$res=json_decode($res,true);
		
		if($res['flag']){
			if($order_excel==1){
				$count=$res['data']['count_data'];
				$page_nums=$count/$push_data['data']['page_size'];
				$this->assign("page_nums",$page_nums);							 
				$this->display('Feestatistical/statistical_excel');
			}else{
				$list=$res['data'];
				foreach($list['detail'] as $k=>$v){
					$list['detail'][$k]['old_order_no']=' '.$v['old_order_no'];
					$list['detail'][$k]['logistics_no']=' '.$v['logistics_no'];
				}
				// $xlsName  = "订单列表";
				// $xlsCell  = array(
					// array('count_time','发货日期'),
					// array('old_order_no','原始单号'),
					// array('logistics_no','运单号'),
					// array('user_name','收件人姓名'),
					// array('goods_name','商品名称'),
					// array('goods_num','商品数量'),
					// array('weight','包裹重量'),
					// array('freight_fee','物流费用'),
					// array('operate_fee','操作费'),
					// array('tax','税金'),
					// array('pt_fee','平台使用费')
				// );
				// $this->exportExcel($xlsName,$xlsCell,$list['detail']);
				$this->export_csv($list['detail']);
				die;
			}
		}else{
			$this->error($res['tip']);
		}
	}
	public function export_ordercsv($data){
		$header = "ID,订单编号,运单号,包裹重量,收件人姓名,收件人电话,省,市,区,收件人地址,商品条形码,商品数量,单价,出库时间\n";
		$header = iconv('GB2312', 'UTF-8', $header); ////将字符串的编码从GB2312转到UTF-8
		foreach($data as $k=>$row){
			$id				=" ".$row['id'];
			$old_order_no	=" ".$row['old_order_no'];
			$logistics_no	=" ".$row['logistics_no'];
			$actual_weight	=" ".$row['actual_weight'];
			$user_name		= iconv('utf-8','gb2312',$row['user_name']);
			$user_phone		=" ".$row['user_phone'];
			$province		= iconv('utf-8','gb2312',$row['province']);
			$city			= iconv('utf-8','gb2312',$row['city']);
			$area			= iconv('utf-8','gb2312',$row['area']);
			$user_address 	= iconv('utf-8','gb2312',$row['user_address']); //中文转码 
			$bar_code 		= " ".$row['bar_code']; 
			$goods_nums 	= " ".$row['goods_nums']; 
			$goods_price 	= " ".$row['goods_price']; 
			$delivery_time 	= " ".$row['delivery_time']; 
			$header .= $id.",".$old_order_no.",".$logistics_no.",".$actual_weight.",".$user_name.",".$user_phone.",".$province.",".$city.",".$area.",".$user_address.",".$bar_code.",".$goods_nums.",".$goods_price.",".$delivery_time."\n"; //用引文逗号分开 
		}
		$filename = date('YmdHis').'.csv'; //设置文件名 
		$this->download_csv($filename,$header); //导出 
	}
	public function export_csv($data){
		$header = "发货日期,原始单号,运单号,收件人姓名,商品名称,商品数量,包裹重量,物流费用,操作费,税金,平台使用费\n";
		// $header = iconv('UTF-8', 'GB2312', $header); ////将字符串的编码从GB2312转到UTF-8
		foreach($data as $k=>$row){
			$count_time		=" ".$row['count_time'];
			$old_order_no	="'".$row['old_order_no'];
			$logistics_no	="'".$row['logistics_no'];
			$goods_num		=" ".$row['goods_num'];
			$weight			=" ".$row['weight'];
			$freight_fee	=" ".$row['freight_fee'];
			$operate_fee	=" ".$row['operate_fee'];
			$tax			=" ".$row['tax'];
			$pt_fee			=" ".$row['pt_fee'];
			$user_name 		= $row['user_name']; //中文转码 
			$goods_name 	= $row['goods_name']; 
			$header .= $count_time.",".$old_order_no.",".$logistics_no.",".$user_name.",".$goods_name.",".$goods_num.",".$weight.",".$freight_fee.",".$operate_fee.",".$tax.",".$pt_fee."\n"; //用引文逗号分开 
		}
		$filename = date('YmdHis').'.csv'; //设置文件名 
		$this->download_csv($filename,$header); //导出 
	}
	public function download_csv($filename,$data) { 
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $data; 
    }
	//批量删除
	public function delAll(){
		$ids=I('ids');
		$map['id']=array('in',$ids);
		$m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$status=$m->where($map)->delete();
		if($status){
			$return['status']=1;
			$return['info']="删除成功";
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['info']="出错";
			$this->ajaxReturn($return);
		}
	}
	public function view_goods(){
		$id=I('id');
		$m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$m_info=$m->find($id);
		$this->assign('vo',$m_info);
		$this->display();
	}
	//批量删除
	public function delAll_storagegoods(){
		$ids=I('ids');
		$map['id']=array('in',$ids);
		$m=M('Goods', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$status=$m->where($map)->delete();
		if($status){
			$return['status']=1;
			$return['info']="删除成功";
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['info']="出错";
			$this->ajaxReturn($return);
		}
	}
	//库存列表
	public function storagegoods(){
		$m=M('Goods', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$goods_no=I('goods_no');
		$goods_name=I('goods_name');
		$goods_brand=I('goods_brand');
		$excel=I('excel');
		$p=I('p')?I('p'):1;
		$listrows=20;
		$firstrow=($p-1)*$listrows;
        if(!empty($goods_no)){
			$map['goods_no'] = array('like','%'.$goods_no.'%');
        }
		if(!empty($goods_name)){
			$map['goods_name'] = array('like','%'.$goods_name.'%');
        }
		if(!empty($goods_brand)){
			$map['goods_brand'] = array('like','%'.$goods_brand.'%');
        }
		$count=$m->where($map)->count();
		$list=$m->where($map)->limit($firstrow.','.$listrows)->order('id desc')->select();
		foreach($list as $k=>$v){
			// $list[$k]['goods_price']=$this->goods_price($v['goods_price']);
			if($excel){
				$list[$k]['goods_no']="'".$v['goods_no'];
				$list[$k]['net_weight']=sprintf("%.2f",$v['net_weight']);
				$list[$k]['gross_weight']=sprintf("%.2f",$v['gross_weight']);
			}
		}
		$Page       = new \Think\Page($count,$listrows);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		if($excel){
			$xlsName  = "商品列表";
			$xlsCell  = array(
				array('goods_name','商品名称'),
				array('goods_no','商品编码'),
				array('goods_brand','品牌'),
				array('goods_marque','型号'),
				array('goods_spec','规格'),
				array('goods_price','价格'),
				array('storage_amount','库存'),
				array('net_weight','净重(g)'),
				array('gross_weight','毛重(g)')
			);
			$this->exportExcel($xlsName,$xlsCell,$list);
			die;
		}
		$this->assign("count",$count);
		$this->assign("list",$list);
		$this->assign('page',$show);// 赋值分页输出
		$this->display();
	}
	public function order_detail(){
		$param = I('param.','','trim');

		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		$g=M('Pushordergoods', C('DB_PREFIX_T'), C('db_config'));
		$p=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
		$pr=M('Product', C('DB_PREFIX_T'), C('db_config'));
		
		$id=$param['id'];
		$p_info=$p->find($id);
		$this->assign('detail',$p_info);
		
		$count=$g->where(array('order_id'=>$id))->count();

		$list=$g->where(array('order_id'=>$id))->select();
		foreach($list as $k=>$v){
			// $list[$k]['goods_price']=$this->goods_price($v['goods_price']);
			if(empty($v['goods_name'])){
				$list[$k]['goods_name']=$pr->where(array('goods_no'=>$v['goods_no']))->getField('name');
				// file_put_contents('./log/order_detail.log',date('Y-m-d H:i:s').$pr->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
			}
		}
		$this->assign('count',$count);
		$this->assign('list',$list);
		$this->display();
	}
	//商品列表
	public function goods(){
		// dump(session());
        $m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$bar_code=I('bar_code');
		
		$goods_no=I('goods_no');
		$goods_name=I('goods_name');
		$excel=I('excel');
		$p=I('p')?I('p'):1;
		$listrows=20;
		$firstrow=($p-1)*$listrows;
		if(!empty($bar_code)){
			$map['bar_code'] = array('like','%'.$bar_code.'%');
        }
        if(!empty($goods_no)){
			$map['goods_no'] = array('like','%'.$goods_no.'%');
        }
		if(!empty($goods_name)){
			$map['goods_name'] = array('like','%'.$goods_name.'%');
        }
		$count=$m->where($map)->count();
		$list=$m->where($map)->limit($firstrow.','.$listrows)->order('id desc')->select();
		$Page       = new \Think\Page($count,$listrows);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		if($excel){
			$xlsName  = "商品列表";
			$xlsCell  = array(
				array('goods_no','商品编码'),
				array('goods_name','商品名称'),
				array('goods_brand','品牌'),
				array('goods_marque','型号'),
				array('goods_spec','规格'),
				array('price','商品价格'),
				array('receive_amount','数量'),
				array('goods_tax','税率(%)'),
				array('bar_code','条形码'),
				array('source_no','料号'),
				array('net_weight','净重'),
				array('gross_weight','毛重')
			);
			$this->exportExcel($xlsName,$xlsCell,$list);
			die;
		}
		$this->assign("count",$count);
		$this->assign("list",$list);
		$this->assign('page',$show);// 赋值分页输出
		$this->display();
    }
		//excel导出方法
	public function exportExcel($expTitle,$expCellName,$expTableData){
			$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
			$fileName = $xlsTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
			$cellNum = count($expCellName);
			$dataNum = count($expTableData);
			//vendor("PHPExcel.PHPExcel");
		   
			//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
			import("Org.Util.PHPExcel");
			import("Org.Util.PHPExcel.Writer.Excel5");
			import("Org.Util.PHPExcel.IOFactory.php");
		   
		   $date = date("Y_m_d",time());
			$fileName .= "_{$date}.xls";

			//创建PHPExcel对象，注意，不能少了\
			$objPHPExcel = new \PHPExcel();
			//$objProps = $objPHPExcel->getProperties();
			
			//$objPHPExcel = new PHPExcel();
			$cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
			
			$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
		    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle);//设置标题
			$objPHPExcel->getActiveSheet(0)->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); //居中
			
			for($i=0;$i<$cellNum;$i++){
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]); 
			} 
			  // Miscellaneous glyphs, UTF-8   
			for($i=0;$i<$dataNum;$i++){
			  for($j=0;$j<$cellNum;$j++){
				$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
			  }             
			}  
			
			header('pragma:public');
			header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
			header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
			$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
			$objWriter->save('php://output');
			exit;
	}
	//批量删除
	/* public function delAll_order(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		$ids=$param['ids'];
		$map['id']=array('in',$ids);
		$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
		$data['status'] = -1;
		$status=$m->where($map)->save($data);
		if($status){
			$return['status']=1;
			$return['info']="删除成功";
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['info']="出错";
			$this->ajaxReturn($return);
		}
	} */
	public function edit_storagegoods(){
		$m=M('Goods', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$id=I('id');
		$data['storage_amount']=I('count');
		
		$res=$m->where(array('id'=>$id))->save($data);
		if($res!==false){
			$this->success('修改成功');
		}else{
			$this->error('修改失败');
		}
		
	}
	//添加
	function add_goodss(){
			$trans=M('', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
			$trans->startTrans();   // 开启事务
			$m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
			$g=M('Goods', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
			$param = I('param.','','trim');
			$param['add_time']=time();
			$bar_code=$param['bar_code'];
			$param['goods_no']=$param['bar_code'];
			$goods_no=$bar_code;//商品编码=条形码
			$nums=$param['receive_amount'];
			$param['storage_amount']=$param['receive_amount'];
			$map['goods_no']=$goods_no;
			if(empty($param['goods_name'])){
				alert_json(0,'商品名称不能为空');
			}
			if(empty($param['bar_code'])){
				alert_json(0,'条形码不能为空');
			}
			if(empty($param['storage_amount'])){
				alert_json(0,'库存不能为空');
			}
			if (!empty($_FILES)){
				$config = array(
					'maxSize'    =>    3145728,    
					'savePath'   =>    '/Import/',    
					'saveName'   =>    array('uniqid',''),    
					'exts'       =>    array('jpg','jpeg','png','gif'),    
					'autoSub'    =>    true,    
					'subName'    =>    array('date','Ymd'),);
				$upload = new \Think\Upload($config);// 实例化上传类
				$info   =   $upload->upload();    
				if(!$info) {// 上传错误提示错误信息        
					$this->error($upload->getError());    
				}
				$extension=$info['goods_pic']['ext'];
				$file_name='./Uploads'.$info['goods_pic']['savepath'].$info['goods_pic']['savename'];
				
				// textgd($file_name);//加水印
				$param['goods_pic']=$file_name;
			}
			// dump($param);
			$res=$m->add($param);
			if($res){
				$g_info=$g->where($map)->find();//更新库存
				if(empty($g_info)){//没商品信息则新增商品信息
					$data_goods['bar_code']=$param['bar_code'];
					$data_goods['goods_no']=$param['goods_no'];
					$data_goods['goods_name']=$param['goods_name'];
					$data_goods['goods_brand']=$param['goods_brand'];
					$data_goods['goods_marque']=$param['goods_marque'];
					$data_goods['goods_spec']=$param['goods_spec'];
					$data_goods['goods_pic']=$param['goods_pic'];
					$data_goods['goods_price']=$param['price'];
					$data_goods['storage_amount']=$param['receive_amount'];//库存数量
					$data_goods['amount']=$param['receive_amount'];//总数量
					$data_goods['net_weight']=$param['net_weight'];
					$data_goods['gross_weight']=$param['gross_weight'];
					$res_goods=$g->add($data_goods);
					if(!$res_goods){
						$trans->rollback();
						alert_json(0,'添加库存信息失败');
					}
				}else{//有商品信息则更新库存
					$this->edit_storagegoodsnums($goods_no,$nums);
				}
				$trans->commit();
				alert_json(1,'添加成功');
			}else{
				$trans->rollback();
				alert_json(0,'添加失败');
			}
	}
	//更新
	function add_goods(){
		if(IS_POST){
			$m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
			$param = I('param.','','trim');
			$param['update_time'] = time();
			$id=$param['id'];
			$param['goods_no']=$param['bar_code'];
			if(empty($param['goods_name'])){
				alert_json(0,'商品名称不能为空');
			}
			if(empty($param['bar_code'])){
				alert_json(0,'条形码不能为空');
			}
			if(empty($param['receive_amount'])){
				alert_json(0,'库存不能为空');
			}
			if (!empty($_FILES)){
				$config = array(
					'maxSize'    =>    3145728,    
					'savePath'   =>    '/Import/',    
					'saveName'   =>    array('uniqid',''),    
					'exts'       =>    array('jpg','jpeg','png','gif'),    
					'autoSub'    =>    true,    
					'subName'    =>    array('date','Ymd'),);
				$upload = new \Think\Upload($config);// 实例化上传类
				$info   =   $upload->upload();    
				if(!$info) {// 上传错误提示错误信息        
					$this->error($upload->getError());    
				}
				$extension=$info['goods_pic']['ext'];
				$file_name='./Uploads'.$info['goods_pic']['savepath'].$info['goods_pic']['savename'];
				$param['goods_pic']=$file_name;
			}
			$res=$m->where(array('id'=>$id))->save($param);
			if($res!==false){
				alert_json(1,'更新成功');
			}
		}else{
			$this->display();
		}
	}
	//编辑
	function edit_goods(){
		$id=trim(I('id'));
		$m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$detail=$m->where(array('id'=>$id))->find();
		$this->assign('detail',$detail);
		$this->display();
	}
	//删除
	function del_goods(){
		$id=trim(I('id'));
		$m=M('ArrivalOrder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$map['id']=$id;
		$status=$m->where($map)->delete();

		if($status!==false){
            echo "y";
        }else{
            echo "操作失败";
        }
	}
	//账册列表
	// public function get_booklist($warehouse_code){
		// $url=C('BASE_CONFIG.get_booklist');
		// $data['warehouse_code']=$warehouse_code;
		// $res=push($url,$data);
		// $res=json_decode($res,true);
		// return $res;
	// }

	//货主列表及配置调用
	public function is_owner($username,$warehouse_code){
		$u=M('User');
		$erp_code=session('company.id');
		$wheres['_string']="FIND_IN_SET($erp_code,erp_code)";
		$u_list=$u->where($wheres)->select();
		// $username=$param['username'];
		if(empty($username)){
			$username=$u_list[0]['username'];
		}
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);//当前
		$base_config=M('Config',C('DB_PREFIX_T'), C('db_config'));
		$list=$base_config->getField('en_name,value');
		C('base_config',$list);
		$uw=M('UserWarehouse');
		$w=M('Warehouse');
		// dump($u_list);
		foreach($u_list as $k=>$v){
			$warehouse_group_id=$uw->where(array('user_id'=>$v['id']))->getField('warehouse_group_id');
			// dump($warehouse_group_id);
			$w_list=$w->field('warehouse_code')->where(array('id'=>array('in',"$warehouse_group_id")))->select();
			$res=deep_in_array($warehouse_code,$w_list);
			if(!$res){
				unset($u_list[$k]);
			}
		}
		$this->assign('u_list',$u_list);
		$this->assign('username',$username);
	}
	//订单列表
	public function order(){
		$param = I('param.','','trim');
		
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		C('URL_MODEL',0);
        $m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
		$g=M('Pushordergoods', C('DB_PREFIX_T'), C('db_config'));
		
		$order_excel=$param['order_excel'];
		
		$push_status=$param['push_status'];
		$order_no=$param['order_no'];
		$logistics_no=$param['logistics_no'];
		$user_name=$param['user_name'];
		$user_idcard=$param['user_idcard'];
		$user_phone=$param['user_phone'];
		$user_address=$param['user_address'];
		$start_time=$param['start_time'];
		$end_time=$param['end_time'];
		
		$delivery_start_time=$param['delivery_start_time'];
		$delivery_end_time=$param['delivery_end_time'];
		
		$flag=$param['flag'];
		$oms_del=$param['oms_del'];
		
		$abnormal=$param['abnormal'];
		
		$warehouse_code=$param['warehouse_code'];//当前仓库编码
		
		!empty($start_time)?$start_time = strtotime($start_time):$start_time=time()-3600*24*30;
		!empty($end_time)?$end_time = strtotime($end_time):$end_time =time();
		$mapstring="add_time>=$start_time AND add_time<=$end_time";
		
		!empty($delivery_start_time)?$delivery_start_time = strtotime($delivery_start_time):$delivery_start_time=0;
		!empty($delivery_end_time)?$delivery_end_time = strtotime($delivery_end_time):$delivery_end_time =time();
		$mapstring.=" and delivery_time>=$delivery_start_time AND delivery_time<=$delivery_end_time";
		$map['_string'] = $mapstring;
		
		if(!empty($flag)){
			$map['flag']=$flag;
		}
		if(!empty($warehouse_code)){
			$map['warehouse_code']=$warehouse_code;
			if(!empty($abnormal)){
				$map['warehouse_code']=array("in","$warehouse_code");
			}
		}
		$map['status']=array('neq',-1);
		$p=I('p')?I('p'):1;
		$listrows=20;
		$firstrow=($p-1)*$listrows;
		
		if(!empty($push_status)){
			if($push_status==1){
				$map['push_status'] = 1;
			}
			if($push_status==-1){
				$map['push_status'] = 0;
			}
			if($push_status==2){
				$map['push_status'] = 2;
			}
        }
		
		if(!empty($oms_del)){
			if($oms_del==1){
				$map['oms_del'] = 1;
			}
        }
		
        if(!empty($order_no)){
			$map['old_order_no'] = array('like','%'.$order_no.'%');
        }
		if(!empty($logistics_no)){
			$map['logistics_no'] = array('like','%'.$logistics_no.'%');
        }
		if(!empty($user_idcard)){
			$map['user_idcard'] = array('like','%'.$user_idcard.'%');
        }
		if(!empty($user_phone)){
			$map['user_phone'] = array('like','%'.$user_phone.'%');
        }
		if(!empty($user_address)){
			$map['user_address'] = array('like','%'.$user_address.'%');
        }
		if(!empty($user_name)){
			$map['user_name'] = array('like','%'.$user_name.'%');
        }
		if(!empty($abnormal)){
			$map['is_pass'] = 0;
            $map['abnormal_price'] = 0;
        }
		$excel=I('excel');
		
		$count=$m->where($map)->count();
		if(!empty($excel)){ //导出Excel
			$p=I('page')?I('page'):1;
			$listrows=2000;
			$firstrow=($p-1)*$listrows;
		}
		$page_nums=$count/2000;
		if(!empty($excel)){ //导出Excel
			foreach($map as $k=>$v){
				if($k=='_string'){
					$mapstring="m.add_time>=$start_time AND m.add_time<=$end_time";
					$mapstring.=" and m.delivery_time>=$delivery_start_time AND m.delivery_time<=$delivery_end_time";
					$map['_string'] = $mapstring;
				}else{
					$map['m.'.$k]=$v;
					unset($map[$k]);
				}
				
			}
			$list=$m->field('m.id,m.old_order_no,m.logistics_no,m.actual_weight,m.user_name,m.user_phone,m.province,m.city,m.area,m.user_address,m.delivery_time,g.bar_code,g.goods_nums,g.goods_price')->alias('m')->join("__PUSHORDERGOODS__ g on m.id=g.order_id","left")->where($map)->limit($firstrow.','.$listrows)->order('m.id desc')->select();
		}else{
			$list=$m->where($map)->limit($firstrow.','.$listrows)->order('id desc')->select();
		}
		
		$Page       = new \Think\Page($count,$listrows);// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出
		// echo $m->getlastsql();
		// dump($list);
		
		//导出Excel
		
		if(!empty($excel)){ //导出Excel
			foreach($list as $k=>$v){
				$list[$k]['old_order_no']=' '.$v['old_order_no'];
				$list[$k]['user_phone']=' '.$v['user_phone'];
				$list[$k]['logistics_no']=' '.$v['logistics_no'];
				$list[$k]['bar_code']=' '.$v['bar_code'];
				$list[$k]['delivery_time']=date("Y-m-d H:i:s",$v['delivery_time']);
			}
			$xlsName  = "订单管理";
			$xlsCell  = array(
				array('id','ID'),
				array('old_order_no','订单编号'),
				array('logistics_no','运单号'),
				array('actual_weight','包裹重量'),
				array('user_name','收件人姓名'),
				array('user_phone','收件人电话'),
				array('province','省'),
				array('city','市'),
				array('area','区'),
				array('user_address','收件人地址'),
				array('bar_code','商品条形码'),
				array('goods_nums','商品数量'),
				array('goods_price','单价'),
				array('delivery_time','出库时间')
			);
			$this->exportExcel($xlsName,$xlsCell,$list);
			// $this->export_ordercsv($list);
			die;
		}
		
		$warehouse=M('Warehouse');//仓库表
		$warehouse_info=$warehouse->where(array('warehouse_code'=>$warehouse_code))->find();
		
		if($warehouse_info['warehouse_cate']==1){//一般仓
			$importExcelPushorderTempName_Normal=1;//配置订单模板(一般正常模板)
		}
		if($warehouse_info['warehouse_cate']==2){//跨境仓
			$importExcelPushorderTempName=C('base_config.importExcelPushorderTempName');//配置跨境定制模板名称
		}

		if(!empty($importExcelPushorderTempName)){
			$this->assign("importExcelPushorderTempName",$importExcelPushorderTempName);
		}else{
			if(!empty($importExcelPushorderTempName_Normal)){
				$this->assign("importExcelPushorderTempName",'1');
			}else{
				$this->assign("importExcelPushorderTempName",'0');
			}
		}
		$this->assign("warehouse_cate",$warehouse_info['warehouse_cate']);//仓库属性
		$this->assign("count",$count);
		$this->assign("list",$list);
		$this->assign('page',$show);// 赋值分页输出
		if($order_excel==1){
			$this->assign("page_nums",$page_nums);
			$this->display('order_excel');
		}else{
			$this->display();
		}
    }

    public function order_price(){
        $param = I('param.','','trim');

        $owner_status=session('company.owner_status');//货主属性0:否1是
        $this->assign('owner_status',$owner_status);
        if(!$owner_status){//不是货主（主erp）
            $this->is_owner($param['username'],$param['warehouse_code']);
        }
        C('URL_MODEL',0);
        $m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
        $g=M('Pushordergoods', C('DB_PREFIX_T'), C('db_config'));

        $order_excel=$param['order_excel'];

        $push_status=$param['push_status'];
        $order_no=$param['order_no'];
        $logistics_no=$param['logistics_no'];
        $user_name=$param['user_name'];
        $user_idcard=$param['user_idcard'];
        $user_phone=$param['user_phone'];
        $user_address=$param['user_address'];
        $start_time=$param['start_time'];
        $end_time=$param['end_time'];

        $delivery_start_time=$param['delivery_start_time'];
        $delivery_end_time=$param['delivery_end_time'];

        $flag=$param['flag'];
        $oms_del=$param['oms_del'];

        $abnormal=$param['abnormal'];

        $warehouse_code=$param['warehouse_code'];//当前仓库编码

        !empty($start_time)?$start_time = strtotime($start_time):$start_time=time()-3600*24*30;
        !empty($end_time)?$end_time = strtotime($end_time):$end_time =time();
        $mapstring="add_time>=$start_time AND add_time<=$end_time";

        !empty($delivery_start_time)?$delivery_start_time = strtotime($delivery_start_time):$delivery_start_time=0;
        !empty($delivery_end_time)?$delivery_end_time = strtotime($delivery_end_time):$delivery_end_time =time();
        $mapstring.=" and delivery_time>=$delivery_start_time AND delivery_time<=$delivery_end_time";
        $map['_string'] = $mapstring;

        if(!empty($flag)){
            $map['flag']=$flag;
        }
        if(!empty($warehouse_code)){
            $map['warehouse_code']=$warehouse_code;
            if(!empty($abnormal)){
                $map['warehouse_code']=array("in","$warehouse_code");
            }
        }
        $map['status']=array('neq',-1);
        $p=I('p')?I('p'):1;
        $listrows=20;
        $firstrow=($p-1)*$listrows;

        if(!empty($push_status)){
            if($push_status==1){
                $map['push_status'] = 1;
            }
            if($push_status==-1){
                $map['push_status'] = 0;
            }
            if($push_status==2){
                $map['push_status'] = 2;
            }
        }

        if(!empty($oms_del)){
            if($oms_del==1){
                $map['oms_del'] = 1;
            }
        }

        if(!empty($order_no)){
            $map['old_order_no'] = array('like','%'.$order_no.'%');
        }
        if(!empty($logistics_no)){
            $map['logistics_no'] = array('like','%'.$logistics_no.'%');
        }
        if(!empty($user_idcard)){
            $map['user_idcard'] = array('like','%'.$user_idcard.'%');
        }
        if(!empty($user_phone)){
            $map['user_phone'] = array('like','%'.$user_phone.'%');
        }
        if(!empty($user_address)){
            $map['user_address'] = array('like','%'.$user_address.'%');
        }
        if(!empty($user_name)){
            $map['user_name'] = array('like','%'.$user_name.'%');
        }
        if(!empty($abnormal)){
            $map['abnormal_price'] = 1;
        }
        $excel=I('excel');

        $count=$m->where($map)->count();
        if(!empty($excel)){ //导出Excel
            $p=I('page')?I('page'):1;
            $listrows=2000;
            $firstrow=($p-1)*$listrows;
        }
        $page_nums=$count/2000;
        if(!empty($excel)){ //导出Excel
            foreach($map as $k=>$v){
                if($k=='_string'){
                    $mapstring="m.add_time>=$start_time AND m.add_time<=$end_time";
                    $mapstring.=" and m.delivery_time>=$delivery_start_time AND m.delivery_time<=$delivery_end_time";
                    $map['_string'] = $mapstring;
                }else{
                    $map['m.'.$k]=$v;
                    unset($map[$k]);
                }

            }
            $list=$m->field('m.id,m.old_order_no,m.logistics_no,m.actual_weight,m.user_name,m.user_phone,m.province,m.city,m.area,m.user_address,m.delivery_time,g.bar_code,g.goods_nums,g.goods_price')->alias('m')->join("__PUSHORDERGOODS__ g on m.id=g.order_id","left")->where($map)->limit($firstrow.','.$listrows)->order('m.id desc')->select();
        }else{
            $list=$m->where($map)->limit($firstrow.','.$listrows)->order('id desc')->select();
        }

        $Page       = new \Think\Page($count,$listrows);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
        // echo $m->getlastsql();
        // dump($list);

        //导出Excel

        if(!empty($excel)){ //导出Excel
            foreach($list as $k=>$v){
                $list[$k]['old_order_no']=' '.$v['old_order_no'];
                $list[$k]['user_phone']=' '.$v['user_phone'];
                $list[$k]['logistics_no']=' '.$v['logistics_no'];
                $list[$k]['bar_code']=' '.$v['bar_code'];
                $list[$k]['delivery_time']=date("Y-m-d H:i:s",$v['delivery_time']);
            }
            $xlsName  = "订单管理";
            $xlsCell  = array(
                array('id','ID'),
                array('old_order_no','订单编号'),
                array('logistics_no','运单号'),
                array('actual_weight','包裹重量'),
                array('user_name','收件人姓名'),
                array('user_phone','收件人电话'),
                array('province','省'),
                array('city','市'),
                array('area','区'),
                array('user_address','收件人地址'),
                array('bar_code','商品条形码'),
                array('goods_nums','商品数量'),
                array('goods_price','单价'),
                array('delivery_time','出库时间')
            );
            $this->exportExcel($xlsName,$xlsCell,$list);
            // $this->export_ordercsv($list);
            die;
        }

        $warehouse=M('Warehouse');//仓库表
        $warehouse_info=$warehouse->where(array('warehouse_code'=>$warehouse_code))->find();

        if($warehouse_info['warehouse_cate']==1){//一般仓
            $importExcelPushorderTempName_Normal=1;//配置订单模板(一般正常模板)
        }
        if($warehouse_info['warehouse_cate']==2){//跨境仓
            $importExcelPushorderTempName=C('base_config.importExcelPushorderTempName');//配置跨境定制模板名称
        }

        if(!empty($importExcelPushorderTempName)){
            $this->assign("importExcelPushorderTempName",$importExcelPushorderTempName);
        }else{
            if(!empty($importExcelPushorderTempName_Normal)){
                $this->assign("importExcelPushorderTempName",'1');
            }else{
                $this->assign("importExcelPushorderTempName",'0');
            }
        }
        $this->assign("warehouse_cate",$warehouse_info['warehouse_cate']);//仓库属性
        $this->assign("count",$count);
        $this->assign("list",$list);
        $this->assign('page',$show);// 赋值分页输出
        if($order_excel==1){
            $this->assign("page_nums",$page_nums);
            $this->display('order_excel');
        }else{
            $this->display();
        }
    }
	//添加
	function add_orders(){
			$param = I('param.','','trim');
			$owner_status=session('company.owner_status');//货主属性0:否1是
			$this->assign('owner_status',$owner_status);
			if(!$owner_status){//不是货主（主erp）
				$this->is_owner($param['username'],$param['warehouse_code']);
			}
			if(empty($param['username'])){
				$username=session('company.username');
			}else{
				$username=$param['username'];
			}
			$warehouse_code=$param['warehouse_code'];
			$trans = M('',C('DB_PREFIX_T'), C('db_config'));
			$trans->startTrans();   // 开启事务
			
			$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
			$g=M('Pushordergoods', C('DB_PREFIX_T'), C('db_config'));
			$p=M('Printorder', C('DB_PREFIX_T'), C('db_config'));
			$pro=M('Product',C('DB_PREFIX_T'), C('db_config'));
			$u=M('User');
			
			$this->verification($param);
			$param['add_time']=time();

			$map['order_no']=I('order_no');
			$duplicate=$m->where($map)->find();
			if($duplicate){
				$return['message']='订单编码已经存在';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			$print_data['sendMan']=$param['sendMan'];
			$print_data['sendManPhone']=$param['sendManPhone'];
			$print_data['sendProvince']=$param['sendProvince'];
			$print_data['sendCity']=$param['sendCity'];
			$print_data['sendCounty']=$param['sendCounty'];
			$print_data['sendManAddress']=$param['sendManAddress'];
			$print_data['receiveMan']=$param['user_name'];
			$print_data['receiveManPhone']=$param['user_phone'];
			$print_data['receiveManAddress']=$param['user_address'];
			$print_data['receiveProvince']=$param['province'];
			$print_data['receiveCity']=$param['city'];
			$print_data['receiveCounty']=$param['area'];
			$print_data['order_no']=$map['order_no'];
			
			unset($param['username']);
			
			$param['old_order_no']='erp'.session('company.id').$param['order_no'];
			$res=$m->add($param);
			// dump($param['warehouse_code']);
			// die;
			if($res){
				$status=$p->add($print_data);//添加面单信息
				if(!$status){
					$trans->rollback();
					alert_json(0,'面单信息添加失败');
				}
				//添加商品详情-begin
				$goodslist=session('goodslist');
				$total_order_tax=0;//全部税金
				foreach($goodslist as $ks=>$vs){
					$goodslist[$ks]['order_id']=$res;

					$goods_info=$pro->where(array('goods_no'=>$vs['goods_no']))->find();
					if(empty($goods_info)){
						$trans->rollback();
						$return['status']=0;
						$return['message']="账册中没有查到对应条码信息【".$vs['bar_code']."】";
						$this->ajaxReturn($return);
					}else{
						if(empty($goods_info['pn'])){
							$trans->rollback();
							$return['status']=0;
							$return['message']="账册中没有查到对应条码信息【".$vs['bar_code']."】对应的料号信息，请完善信息后再导入";
							$this->ajaxReturn($return);
						}
						if(empty($goods_info['net_weight'])){
							$trans->rollback();
							$return['status']=0;
							$return['message']="账册中没有查到对应条码信息【".$vs['bar_code']."】对应的净重，请完善信息后再导入";
							$this->ajaxReturn($return);
						}
						if(empty($goods_info['gross_weight'])){
							$trans->rollback();
							$return['status']=0;
							$return['message']="账册中没有查到对应条码信息【".$vs['bar_code']."】对应的毛重，请完善信息后再导入";
							$this->ajaxReturn($return);
						}
						if(empty($goods_info['goods_tax'])){
							$trans->rollback();
							$return['status']=0;
							$return['message']="账册中没有查到对应条码信息【".$vs['bar_code']."】对应的税率，请完善信息后再导入";
							$this->ajaxReturn($return);
						}
					}
				
					$order_tax=0;//订单总税金
					$goods_price=sprintf("%.2f",$vs['goods_price']*$vs['goods_nums']);//商品总价格=单价*数量
					file_put_contents('./log/goods_price.log',date('Y-m-d H:i:s').var_export($vs['goods_price'],true).PHP_EOL,FILE_APPEND);//日志导出sql
					$ems_fee=0;//运费
					$insure_amount=0;//保费
					$consumption_rate=$goods_info['consumption_rate'];//消费税率
					$increment_rate=$goods_info['increment_rate'];//增值税率
					$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
					
					$total_price+=$goods_price;//总价格(不含税)
					if($total_price>=2000){
						$trans->rollback();
						alert_json(0,'总价格['.$total_price.']'."订单总金额不能大于2000");
					}
					$order_tax+=$goods_tax;//订单总税金
					$total_order_tax+=$goods_tax;//全部税金
				}
				$res_g=$g->addAll($goodslist);
				if(!$res_g){
					$trans->rollback();
					alert_json(0,'订单商品添加失败');
				}
				//添加商品详情-end
				$push_data['detail'][$ks]['goods_detail_id']=$res_g;//商品详细id
				$push_data['detail'][$ks]['goods_nums']=$vs['goods_nums'];//数量
				$push_data['detail'][$ks]['goods_no']=$vs['goods_no'];//商品编码
					
				$api_url="http://www.t-cang.com/oms/index.php/Api/ErpApi/frozen_money";//保证金扣费预估接口
				$api_url_un="http://www.t-cang.com/oms/index.php/Api/ErpApi/unfreeze_money";//保证金扣费预估(释放金额)接口
				$u_info=$u->where(array('username'=>$username))->find();
				
				$api_push_data['customer']['user_code']=$u_info['user_code'];
				$api_push_data['customer']['user_key']=$u_info['user_key'];
				$api_push_data['data']['order_tax']=$total_order_tax;
				$api_res=push($api_url,$api_push_data);

				$api_res=json_decode($api_res,true);
				file_put_contents('./log/order_tax.log',date('Y-m-d H:i:s').var_export($vs['goods_price'],true).PHP_EOL,FILE_APPEND);//日志导出sql
				file_put_contents('./log/order_tax.log',date('Y-m-d H:i:s').var_export($api_push_data,true).PHP_EOL,FILE_APPEND);//日志导出sql
				if(!$api_res['flag']){
					$trans->rollback();
					alert_json(0,$api_res['tip']);
				}
				//扣库存-begin
				// $push_data['warehouse_code']='12345678';//仓库编码
				// $push_data['warehouse_code']='11330213';//仓库编码(下沙仓)
				$push_data['warehouse_code']=I('warehouse_code');
				
				$url=C('base_config.freez_storage');
				if(empty($url)){
					alert_json(0,'请配置冻结库存接口');
				}
				$res_edit=push($url,$push_data);
				$res_edit=json_decode($res_edit,true);
				file_put_contents('./log/freez_storage.log',date('Y-m-d H:i:s').var_export($res_edit,true).PHP_EOL,FILE_APPEND);//日志导出sql
				if(!$res_edit['status']){
					//释放冻结金额-begin
						$api_res_un=push($api_url_un,$api_push_data);
					//释放冻结金额-end
					$trans->rollback();
					alert_json(0,$res_edit['message']);
				}else{
					foreach($res_edit['detail'] as $kss=>$vss){
						$map_p['id']=$vss['goods_detail_id'];//订单明细对应商品id
						$data_p['goods_batch_no']=$vss['str'];//关联批次和数量
						//$data_p['goods_batch_no']=array('exp',"concat(goods_batch_no,',$str')");//关联批次和数量
						$g->where($map_p)->save($data_p);
					}
				}
				//扣库存-end
				$trans->commit();
				session('goodslist',"");
				$return['message']='添加成功';
				$return['status']=true;
				$this->ajaxReturn($return);
			}
	}
	//验证
	public function verification($param){
			if(empty($param['order_no'])){
				$return['message']='订单编号不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			// if(empty($param['logistics_no'])){
				// $return['message']='电子面单号不能为空';
				// $return['status']=false;
				// $this->ajaxReturn($return);
			// }
			if(!mobile($param['user_phone'])){
				$return['message']='收件人电话(手机号)错误';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if(empty($param['user_name'])){
				$return['message']='收件人姓名不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			// if(empty($param['user_idcard'])){
				// $return['message']='身份证号不能为空';
				// $return['status']=false;
				// $this->ajaxReturn($return);
			// }
			if(empty($param['user_phone'])){
				$return['message']='收件人电话不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if(empty($param['province'])){
				$return['message']='到件省不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if(empty($param['city'])){
				$return['message']='到件市不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if(empty($param['area'])){
				$return['message']='到件区/县不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if(empty($param['user_address'])){
				$return['message']='详细地址不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if(empty($param['total_price'])){
				$return['message']='总价不能为空';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			// if(strlen($param['user_idcard'])!=15 and strlen($param['user_idcard'])!=18){
				// $return['message']='身份证号位数必须为15位或18位';
				// $return['status']=false;
				// $this->ajaxReturn($return);
			// }
	}
	public function city_list(){
		$code=I('code');
		$city_list=city_list($code);
		alert_json(1,$city_list);
	}
	public function area_list(){
		// dump(I());
		// die;
		$code=I('code');
		$province_name=I('province_name');
		$area_list=area_list($province_name,$code);
		alert_json(1,$area_list);
	}
	//推送备注信息
	public function pushwms($id,$warehouse_code){
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$data=$m->field('logistics_no,erp_mark_mailno')->where(array('id'=>$id))->find();
		$data['warehouse_code']=$warehouse_code;
		$url=C('BASE_CONFIG.pushwms_mark');
		$res=push($url,$data);

		$res=json_decode($res,true);
		if($res['status']){
			alert_json(1,'成功!');
		}else{
			alert_json(1,$res['message']);
		}
	}
	

	public function add_order_list(){
		$param=I('param.','','trim');
		if(!empty($param['goods_nums'])){
			$goods_nums=explode(",",$param['goods_nums']);
			$goodslist=session("goodslist");
			foreach($goodslist as $k=>$v){
				$goodslist[$k]['goods_nums']=$goods_nums[$k];
			}
			session("goodslist",$goodslist);
		}
		$outbound=A('Outbound');
		$username=I('username');
		if(empty($username)){
			$username=session("company.username");
		}
		$warehouse_code=I('warehouse_code');
		$serialNumber=$outbound->serialNumber('Pushorder',$username,$warehouse_code);
		$serialNumber='P'.date("Ymd",time()).$serialNumber;
		$this->assign("serialNumber",$serialNumber);
		
		$province_list=province_list();
		$this->assign('province_list',$province_list);
		$this->display('add_order');
	}
	//更新
	function add_order(){
		$province_list=province_list();
		$this->assign('province_list',$province_list);
		
		//流水号
		$outbound=A('Outbound');
		$username=I('username');
		$warehouse_code=I('warehouse_code');
		$serialNumber=$outbound->serialNumber('Pushorder',$username,$warehouse_code);
		$serialNumber='P'.date("Ymd",time()).$serialNumber;
		$this->assign("serialNumber",$serialNumber);
		//流水号
		if(IS_POST){
			$param = I('param.','','trim');
			$id=$param['id'];
			$owner_status=session('company.owner_status');//货主属性0:否1是
			$this->assign('owner_status',$owner_status);
			if(!$owner_status){//不是货主（主erp）
				$this->is_owner($param['username'],$param['warehouse_code']);
			}
			$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
			$p=M('Printorder', C('DB_PREFIX_T'), C('db_config'));
			$m_info=$m->where(array('id'=>$id))->find();
			$this->verification($param);
			
			$print_data['sendMan']=$param['sendMan'];
			$print_data['sendManPhone']=$param['sendManPhone'];
			$print_data['sendProvince']=$param['sendProvince'];
			$print_data['sendCity']=$param['sendCity'];
			$print_data['sendCounty']=$param['sendCounty'];
			$print_data['sendManAddress']=$param['sendManAddress'];
			$print_data['receiveMan']=$param['user_name'];
			$print_data['receiveManPhone']=$param['user_phone'];
			$print_data['receiveManAddress']=$param['user_address'];
			$print_data['receiveProvince']=$param['province'];
			$print_data['receiveCity']=$param['city'];
			$print_data['receiveCounty']=$param['area'];
			
			$param['update_time'] = time();
			
			$order_no=$param['order_no'];
			unset($param['order_no']);
			$res=$m->where(array('id'=>$id))->save($param);
			if($res!==false){
				$warehouse_code=$param['warehouse_code'];
				if($m_info['push_status']){
					if(!empty($param['erp_mark_mailno'])){
						$this->pushwms($id,$warehouse_code);
					}
				}
				$status=$p->where(array('order_no'=>$order_no))->save($print_data);
				if($status===false){
					$return['message']='更新面单信息失败';
					$return['status']=false;
					$this->ajaxReturn($return);
				}
				$return['message']='更新成功';
				$return['status']=true;
				$this->ajaxReturn($return);
			}
		}else{
			$this->display();
		}
	}
	// public function pushselect(){
		// $m=M('Pushorder', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		// $param=I('param.','','trim');
		// $ids=$param['ids'];
		// $url=C('base_config.orderselect');
		// $map['id']=array('in',$ids);
		// $list=$m->field('order_no')->where($map)->select();
		// foreach($list as $k=>$v){
			// $res=send_curl($url,$v['order_no']);
			// $res=json_decode($res,true);
			// if($res['flag']){
				// continue;
			// }else{
				// $return['message']=$res['tip'];
				// $return['status']=false;
				// $this->ajaxReturn($return);
			// }
		// }
		// $return['message']=$res['tip'];
		// $return['status']=true;
		// $this->ajaxReturn($return);
	// }
	
	//购买人
	public function edit_buyer(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		$id=$param['id'];
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$info=$m->field('buyer_idcard,buyer_name')->where(array('id'=>$id))->find();
		
		$this->assign('detail',$info);
		$this->display();
	}
	//编辑购买人信息
	public function confirm_edit_buyer(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}

		$id=$param['id'];
		$data['buyer_name']=$param['buyer_name'];
		$data['buyer_idcard']=$param['buyer_idcard'];
		
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$res=$m->where(array('id'=>$id))->save($data);

		if($res!==false){
			alert_json(1,'成功');
		}else{
			alert_json(0,'失败');
		}
	}

	//编辑价格
    public function edit_price(){
        $param = I('param.','','trim');
        $owner_status=session('company.owner_status');//货主属性0:否1是
        $this->assign('owner_status',$owner_status);
        if(!$owner_status){//不是货主（主erp）
            $this->is_owner($param['username'],$param['warehouse_code']);
        }
        $id=$param['id'];
//        $m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
//        $info=$m->field('buyer_idcard,buyer_name')->where(array('id'=>$id))->getField();
        $p=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
        $info = $p->where(array('order_id'=>$id))->select();
        $this->assign('detail',$info);
        $this->display();
    }

    //
    public function confirm_edit_price(){
        $param = I('param.','','trim');
        $order_id = $param['id'];
        $update_data = $param['data'];
        if(empty($update_data)){
            alert_json(0,'操作错误');
        }

        $update = [];
        foreach ($update_data as $k=>$value){
            $goods_info = explode(':',$value);
            $data['order_id']=$order_id;
            $data['goods_price']=$goods_info[1];
            $data['id']=$goods_info[0];
            $m=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
            $res=$m->where(array('id'=>$goods_info[0]))->save($data);
            if($res){
                $update[$k]=1;
            }
        }

        if(!empty($update)){
            alert_json(1,'成功');
        }else{
            alert_json(0,'失败');
        }
    }

    public function confirm_price(){
        $ids=I('ids');
//        $owner_status=session('company.owner_status');//货主属性0:否1是
//        $this->assign('owner_status',$owner_status);
//        if(!$owner_status){//不是货主（主erp）
//            $this->is_owner($param['username'],$param['warehouse_code']);
//        }
//        $ids=I('ids');

//        $ids=$param['id'];

        $map['id']=array('in',$ids);

        $m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
        $res=$m->where($map)->save(array('abnormal_price'=>0));
        if($res!==false){
            alert_json(1,'确认成功');
        }else{
            alert_json(0,'失败');
        }

    }
	//再次推送
	public function pushoms_two(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');

		// dump($param);
		$ids=$param['ids'];
		$url=C('base_config.pushoms_two');
		// dump($url);
		// die;
		$map['id']=array('in',$ids);
		$list=$m->field('id,old_order_no order_no,buyer_name,buyer_idcard')->where($map)->select();
		// echo $m->getlastsql();
		
		$data['data']=$list;
		
		if(!$owner_status){//不是货主（主erp）
			$u_info=$u->where(array('username'=>$param['username']))->find();
			$data['customer']['user_code']=$u_info['user_code'];
			$data['customer']['user_key']=$u_info['user_key'];
		}else{
			$data['customer']['user_code']=session('company.user_code');
			$data['customer']['user_key']=session('company.user_key');
		}

		$data['unusual_order']=1;
		//dump($list);
		//die;
		file_put_contents('./log/pushoms_two'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$res=send_curl($url,$data);
		$res=json_decode($res,true);
		
		if($res['flag']){
			$m->where($map)->save(array('is_pass'=>NULL,'pushtwo_status'=>1));
			$return['message']=$res['tip'];
			$return['status']=1;
			$this->ajaxReturn($return);
		}else{
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=0;
			$this->ajaxReturn($return);
		}
	}
	
	//全部推送
	public function pushoms_all(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		$p=M('PushorderCron');
		$pc=M('PushorderCronDetail');
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		
		// $m_list=$m->field('id')->where(array('status'=>1,'push_status'=>0,'is_pass'=>array('exp','is null')))->select();
		$m_list=$m->field('id')->where(array('status'=>1,'push_status'=>0))->select(); 

		if(empty($m_list)){
			alert_json(0,'没有要推送的新订单');
			die;
		}
		$data_p['warehouse_code']=$param['warehouse_code'];
		
		if(empty($param['username'])){
			$data_p['username']=session('company.username');
		}else{
			$data_p['username']=$param['username'];
		}
		
		$data_p['add_time']=time();

		$p_res=$p->add($data_p);
		if(!$p_res){
			alert_json(0,'添加计划任务失败');
		}else{
			$data=array();
			$ids=array();
			$time=time();
			foreach($m_list as $k=>$v){
				$data[$k]['order_id']=$v['id'];
				$data[$k]['add_time']=$time;
				$data[$k]['porder_id']=$p_res;
				$ids[]=$v['id'];
			}
			$res=$pc->addAll($data);
			if(!$res){
				alert_json(0,'失败');
			}else{
				$res_m=$m->where(array('id'=>array('in',$ids)))->save(array('push_status'=>2));
				alert_json(1,'推送成功'.count($m_list).'条');
			}
		}
	}
	//订单推送(一般正常)
	public function pushoms_normal_normal(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');

		$ids=$param['ids'];
		$url=C('base_config.pushoms_normal');
		$map['id']=array('in',$ids);
		if(!$owner_status){//不是货主（主erp）
			$erp_code=$u->where(array('username'=>$param['username']))->getField('id');//货主erp账号id(erp_code)
		}else{
			$erp_code=session('company.id');
		}
		$list=$m->field("push_status,id,old_order_no order_no,user_name,user_phone,total_price order_amount,province user_province,city user_city,area user_area,user_address,erp_mark_mailno remark,$erp_code erp_code,transport_cate,'ERP' platform_name,cod,cod_money")->where($map)->select();
		// echo $m->getlastsql();
		foreach($list as $k=>$v){
			if($v['push_status']==1){
				$return['message']=$v['order_no'].'已推送';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if($v['push_status']==2){
				$return['message']=$v['order_no'].'正在推送';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			$list[$k]['order_detail']=$g->alias('g')->field('g.goods_no goods_sn,p.name goods_name,g.goods_price,sum(g.goods_nums) goods_nums,g.goods_batch_no')->join('(select * from erp_product where examined=2  group by goods_no) p on g.goods_no=p.goods_no','left')->where(array('order_id'=>$v['id']))->group('g.goods_no')->select();
			// echo $g->getlastsql();
			foreach($list[$k]['order_detail'] as $ks=>$vs){
				// $list[$k]['order_detail'][$ks]['warehouse_code']=C('base_config.warehouse_code_normal');
				$list[$k]['order_detail'][$ks]['warehouse_code']=I('warehouse_code');
				if(empty($vs['goods_price']) or $vs['goods_price']=='0.00'){
					$list[$k]['order_detail'][$ks]['goods_price']=$p->where(array('goods_no'=>$vs['goods_sn']))->getField('price');
				}
			}
		}
		$data['data']=$list;
		if(!$owner_status){//不是货主（主erp）
			$u_info=$u->where(array('username'=>$param['username']))->find();
			$data['customer']['user_code']=$u_info['user_code'];
			$data['customer']['user_key']=$u_info['user_key'];
		}else{
			$data['customer']['user_code']=session('company.user_code');
			$data['customer']['user_key']=session('company.user_key');
		}
		
		$data['trade_model']=0;//非跨境
		file_put_contents('./log/pushoms_normal_normal'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		$res=send_curl($url,$data);
		$res=json_decode($res,true);
		$setstatus['push_status']=1;
		if($res['flag']){
			$m->where($map)->save($setstatus);
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			$this->ajaxReturn($return);
		}else{
			//更新状态-begin
			foreach($res['data']['detail'] as $ks=>$vs){
				// $map_order['old_order_no'][]=$vs['order_no'];
				if(!empty($vs['logistics_no'])){
					$data_order['logistics_no']=$vs['logistics_no'];
					$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
				}else{
					$old_order_no[]=$vs['order_no'];
				}
			}
			// if(!empty($old_order_no)){
				// $map_order['old_order_no']=array('in',$old_order_no);
				// $list_m=$m->field('id')->where($map_order)->select();
				// foreach($list_m as $k=>$v){
					// $ids_m[]=$v['id'];
				// }
				// $idss=array_diff_assoc($ids,$ids_m);
				// $map_m['id']=array('in',$idss);
				// $data_order['push_status']=0;
				// $m->where($map_m)->save($data_order);
			// }
			
			//重复订单直接更新推送状态
			if(!empty($old_order_no)){
				$map_order['old_order_no']=array('in',$old_order_no);
				$data_order['push_status']=1;
				$m->where($map_order)->save($data_order);
			}
			
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=false;
			$this->ajaxReturn($return);
		}
	}
	//订单推送(跨境正常)
	public function pushoms_normal(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');
		
		$ids=$param['ids'];
		$url=C('base_config.pushoms_aozhou');
		$map['id']=array('in',$ids);
		if(!$owner_status){ //不是货主（主erp）
			$erp_code=$u->where(array('username'=>$param['username']))->getField('id');//货主erp账号id(erp_code)
		}else{
			$erp_code=session('company.id');
		}
		$list=$m->field("push_status,id,old_order_no order_no,user_name,user_phone,user_phone buyer_phone,user_idcard,buyer_idcard,buyer_name,apply_logistics,logiscompany_code,logistics_no,province user_province,city user_city,erp_mark_mailno remark,$erp_code erp_code,area user_area,user_address,pay_number,paycompany_code,discount,ems_fee,ems_fee order_freight,insure_amount,goods_tax,come_from,cod,cod_money")->where($map)->select();
		// echo $m->getlastsql();
		foreach($list as $k=>$v){
			if($v['push_status']==1){
				$return['message']=$v['order_no'].'已推送';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if($v['push_status']==2){
				$return['message']=$v['order_no'].'正在推送';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			$list[$k]['order_detail']=$g->alias('g')->field('g.goods_no goods_sn,p.name goods_name,sum(g.goods_nums) goods_nums,g.goods_price,g.goods_batch_no')->join('(select * from erp_product where examined=2  group by goods_no) p on g.goods_no=p.goods_no','left')->where(array('order_id'=>$v['id']))->group('g.goods_no')->select();
			$total_price=0;//订单商品的总销售价格
			$order_tax=0;//订单总税金
			$total_goods_price=0;//兼容小红书导单
			foreach($list[$k]['order_detail'] as $ks=>$vs){
				$goods_info=$p->where(array('goods_no'=>$vs['goods_sn']))->find();
				$list[$k]['order_detail'][$ks]['source_no']=$goods_info['pn'];
				if(empty($vs['goods_price']) or $vs['goods_price']=='0.00'){
					$list[$k]['order_detail'][$ks]['goods_price']=sprintf("%.2f",$goods_info['price']);
				}else{
					$goods_info['price']=$vs['goods_price'];
				}
				//博奥百世推单-begin
				// if($vs['goods_sn']=='91330109BA851562031151'){
					// $goods_info['price']=34;
					// $list[$k]['order_detail'][$ks]['goods_price']=34;
				// }
				//博奥百世推单-begin
				$list[$k]['order_detail'][$ks]['net_weight']=$goods_info['net_weight'];
				$list[$k]['order_detail'][$ks]['gross_weight']=$goods_info['gross_weight'];
				$goods_price=sprintf("%.2f",$goods_info['price']*$vs['goods_nums']);//商品总价格=单价*数量
				// $goods_tax=sprintf("%.2f",$goods_price*$goods_info['goods_tax']);//税金=商品总价格*税率

				$ems_fee=$v['ems_fee'];
				//博奥百世推单-begin
				// if(!empty($v['apply_logistics'])){	//物流已申报
					// $ems_fee=12;//运费
				// }
				//博奥百世推单-begin
				$insure_amount=$v['insure_amount'];//保费

				$consumption_rate=$goods_info['consumption_rate'];//消费税率
				$increment_rate=$goods_info['increment_rate'];//增值税率
				
				$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
				$total_price+=$goods_price;//商品的总销售价格
				$order_tax+=$goods_tax;//订单总税金
				$total_goods_price+=$goods_price;
			}
			if(empty($v['buyer_name'])){//购买人为空
				$list[$k]['buyer_name']=$list[$k]['user_name'];
			}
			$discount=empty($v['discount'])?0:$v['discount'];

			$list[$k]['order_amount']=round($total_price+$ems_fee+$insure_amount+$order_tax,2);//申报总价=商品总价+运费+保费+税
			$list[$k]['set_order_amount']=$list[$k]['order_amount'];
			$list[$k]['order_tax']=round($order_tax,2);
		}
		$data['data']=$list;
		if(!$owner_status){//不是货主（主erp）
			$u_info=$u->where(array('username'=>$param['username']))->find();
			$data['customer']['user_code']=$u_info['user_code'];
			$data['customer']['user_key']=$u_info['user_key'];
		}else{
			$data['customer']['user_code']=session('company.user_code');
			$data['customer']['user_key']=session('company.user_key');
		}
		file_put_contents('./log/pushoms_normal'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$res=send_curl($url,$data);
		$res=json_decode($res,true);

		$setstatus['push_status']=1;
		if($res['flag']){
			$m->where($map)->save($setstatus);
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			$this->ajaxReturn($return);
		}else{
			//更新状态-begin
			foreach($res['data']['detail'] as $ks=>$vs){
				// $map_order['old_order_no'][]=$vs['order_no'];
				if(!empty($vs['logistics_no'])){
					$data_order['logistics_no']=$vs['logistics_no'];
					$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
				}else{
					$old_order_no[]=$vs['order_no'];
				}
			}
			// if(!empty($old_order_no)){
				// $map_order['old_order_no']=array('in',$old_order_no);
				// $list_m=$m->field('id')->where($map_order)->select();
				// foreach($list_m as $k=>$v){
					// $ids_m[]=$v['id'];
				// }
				// $idss=array_diff_assoc($ids,$ids_m);
				// $map_m['id']=array('in',$idss);
				// $data_order['push_status']=0;
				// $m->where($map_m)->save($data_order);
			// }
			
			//重复订单直接更新推送状态
			if(!empty($old_order_no)){
				$map_order['old_order_no']=array('in',$old_order_no);
				$data_order['push_status']=1;
				$m->where($map_order)->save($data_order);
			}
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=false;
			$this->ajaxReturn($return);
		}
	}
	//订单推送(澳洲)
	public function pushoms_aozhou(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));
		$p=M('Product',C('DB_PREFIX_T'),C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'),C('db_config'));
		$u=M('User');
		
		$ids=$param['ids'];
		
		$url=C('base_config.pushoms_aozhou');
		// dump($url);
		// die;
		$map['id']=array('in',$ids);
		if(!$owner_status){//不是货主（主erp）
			$erp_code=$u->where(array('username'=>$param['username']))->getField('id');//货主erp账号id(erp_code)
		}else{
			$erp_code=session('company.id');
		}
		
		$list=$m->field("push_status,id,old_order_no order_no,user_name,user_phone,user_phone buyer_phone,user_idcard,buyer_idcard,buyer_name,apply_logistics,logiscompany_code,logistics_no,province user_province,erp_mark_mailno remark,$erp_code erp_code,city user_city,area user_area,user_address,pay_number,paycompany_code,discount,ems_fee,ems_fee order_freight,insure_amount,goods_tax,come_from,cod,cod_money")->where($map)->select();

		file_put_contents('./log/pushoms_aozhou'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($m->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
		//错误料号9344949001140/9344949001287修正计数器-begin
		$m_e=M('CountView',C('DB_PREFIX_T'),C('db_config'));
		$err_count=$m_e->where(array('id'=>1))->getField('count');
		//错误料号9344949001140/9344949001287修正计数器-end
		foreach($list as $k=>$v){
			if(empty($v['buyer_idcard'])){
				$list[$k]['buyer_idcard']=$v['user_idcard'];
			}
			if($v['push_status']==1){
				$return['message']=$v['order_no'].'已推送';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			if($v['push_status']==2){
				$return['message']=$v['order_no'].'正在推送';
				$return['status']=false;
				$this->ajaxReturn($return);
			}
			$list[$k]['order_detail']=$g->field('goods_no goods_sn,goods_name,goods_nums,goods_price,goods_batch_no')->where(array('order_id'=>$v['id']))->select();
			$total_price=0;//订单总价格
			$order_tax=0;//订单总税金
			foreach($list[$k]['order_detail'] as $ks=>$vs){
				$goods_info=$p->where(array('goods_no'=>$vs['goods_sn']))->find();
				$list[$k]['order_detail'][$ks]['source_no']=$goods_info['pn'];
				//错误料号9344949001140/9344949001287修正计数器-begin
					if($goods_info['pn']=='9344949001140'){
						if($err_count+$vs['goods_nums']<=72){
							$list[$k]['order_detail'][$ks]['source_no']='9344949001287';
						}
					}
				//错误料号9344949001140/9344949001287修正计数器-end
				
				if(empty($vs['goods_price']) or $vs['goods_price']=='0.00'){
					$list[$k]['order_detail'][$ks]['goods_price']=sprintf("%.2f",$goods_info['price']);
				}else{
					$goods_info['price']=$vs['goods_price'];
				}
				$list[$k]['order_detail'][$ks]['goods_price']=sprintf("%.2f",$goods_info['price']);
				$list[$k]['order_detail'][$ks]['net_weight']=$goods_info['net_weight'];
				$list[$k]['order_detail'][$ks]['gross_weight']=$goods_info['gross_weight'];
				$goods_price=sprintf("%.2f",$goods_info['price']*$vs['goods_nums']);//商品总价格=单价*数量
				// $goods_tax=sprintf("%.2f",$goods_price*$goods_info['goods_tax']);//税金=商品总价格*税率
				$ems_fee=$v['ems_fee'];//运费
				$insure_amount=$v['insure_amount'];//保费
				$consumption_rate=$goods_info['consumption_rate'];//消费税率
				$increment_rate=$goods_info['increment_rate'];//增值税率
				
				$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
				$total_price+=$goods_price;//总价格
				$order_tax+=$goods_tax;//订单总税金
			}
			if(empty($v['buyer_name'])){//购买人为空
				$list[$k]['buyer_name']=$list[$k]['user_name'];
			}
			$discount=empty($v['discount'])?0:$v['discount'];
			
			$list[$k]['order_amount']=round($total_price+$ems_fee+$insure_amount+$order_tax,2);//申报总价=商品总价+运费+保费+税
			$list[$k]['order_tax']=round($order_tax,2);

		}
		$data['data']=$list;

		if(!$owner_status){//不是货主（主erp）
			$u_info=$u->where(array('username'=>$param['username']))->find();
			$data['customer']['user_code']=$u_info['user_code'];
			$data['customer']['user_key']=$u_info['user_key'];
		}else{
			$data['customer']['user_code']=session('company.user_code');
			$data['customer']['user_key']=session('company.user_key');
		}
		file_put_contents('./log/pushoms_aozhou'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		$res=send_curl($url,$data);
		$res=json_decode($res,true);

		$setstatus['push_status']=1;
		if($res['flag']){
			//错误料号9344949001140/9344949001287修正计数器-begin
			foreach($list as $k=>$v){
				foreach($list[$k]['order_detail'] as $ks=>$vs){
					$goods_info=$p->where(array('goods_no'=>$vs['goods_sn']))->find();
					//错误料号9344949001140/9344949001287修正计数器-begin
						if($goods_info['pn']=='9344949001140'){
							if($err_count+$vs['goods_nums']<=72){
								$err_count+=$vs['goods_nums'];
								$data_count['count']=$err_count;
								$data_count['update_time']=time();
								$m_e->where(array('id'=>1))->save($data_count);
							}
						}
					//错误料号9344949001140/9344949001287修正计数器-end
				}
			}
			//错误料号9344949001140/9344949001287修正计数器-end
			
			$m->where($map)->save($setstatus);
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			$this->ajaxReturn($return);
		}else{
			//更新状态-begin
			foreach($res['data']['detail'] as $ks=>$vs){
				// $map_order['old_order_no'][]=$vs['order_no'];
				if(!empty($vs['logistics_no'])){
					$data_order['logistics_no']=$vs['logistics_no'];
					$m->where(array('old_order_no'=>$vs['order_no']))->save($data_order);
				}else{
					$old_order_no[]=$vs['order_no'];
				}
			}
			// if(!empty($old_order_no)){
				// $map_order['old_order_no']=array('in',$old_order_no);
				// $list_m=$m->field('id')->where($map_order)->select();
				// foreach($list_m as $k=>$v){
					// $ids_m[]=$v['id'];
				// }
				// $idss=array_diff_assoc($ids,$ids_m);
				// $map_m['id']=array('in',$idss);
				// $data_order['push_status']=0;
				// $m->where($map_m)->save($data_order);
			// }
			
			//重复订单直接更新推送状态
			if(!empty($old_order_no)){
				$map_order['old_order_no']=array('in',$old_order_no);
				$data_order['push_status']=1;
				$m->where($map_order)->save($data_order);
			}
			//更新状态-end
			$return['message']=$res['tip'];
			$return['status']=false;
			$this->ajaxReturn($return);
		}
	}
	
	//推送oms
	public function pushoms(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
		$g=M('Pushordergoods', C('DB_PREFIX_T'), C('db_config'));

		$ids=$param['ids'];
		$url=C('base_config.pushoms');
		$map['id']=array('in',$ids);
		$list=$m->field('id,old_order_no order_no,user_name,user_phone,user_idcard buyer_idcard,user_name buyer_name,province user_province,city user_city,area user_area,user_address,total_price order_amount')->where($map)->select();
		foreach($list as $k=>$v){
			$list[$k]['order_detail']=$g->field('goods_no goods_sn,goods_name,goods_nums,goods_price')->where(array('order_id'=>$v['id']))->select();
		}
		$data['data']=$list;
		$u=M('User');
		if(!$owner_status){//不是货主（主erp）
			$u_info=$u->where(array('username'=>$param['username']))->find();
			$data['customer']['user_code']=$u_info['user_code'];
			$data['customer']['user_key']=$u_info['user_key'];
		}else{
			$data['customer']['user_code']=session('company.user_code');
			$data['customer']['user_key']=session('company.user_key');
		}
		// dump($data);
		$res=send_curl($url,$data);
		$res=json_decode($res,true);
		if($res['flag']){
			//更新运单号
			foreach($res['data']['detail'] as $ks=>$vs){
				$data_order['logistics_no']=$vs['logistics_no'];
				$m->where(array('order_no'=>$vs['order_no']))->save($data_order);
			}
			$return['message']=$res['tip'];
			$return['status']=true;
			$this->ajaxReturn($return);
		}else{
			$return['message']=$res['tip'];
			$return['status']=false;
			$this->ajaxReturn($return);
		}
	}
	//编辑
	function edit_order(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		
		$id=$param['id'];
		$m=M('Pushorder', C('DB_PREFIX_T'), C('db_config'));
		$detail=$m->where(array('id'=>$id))->find();
		
		$province_list=province_list();
		$this->assign('province_list',$province_list);
		$city_list=city_list($detail['province']);
		$this->assign('city_list',$city_list);
		$area_list=area_list($detail['province'],$detail['city']);
		$this->assign('area_list',$area_list);
		
		$send_city_list=city_list($detail['sendprovince']);
		$this->assign('send_city_list',$send_city_list);
		$send_area_list=area_list($detail['sendprovince'],$detail['sendcity']);
		$this->assign('send_area_list',$send_area_list);
		
		$this->assign('detail',$detail);
		$this->display();
	}

	//删除
	public function del_order(){
		// $param = I('param.','','trim');
		// file_put_contents('./log/del_order.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param=array (
		  'warehouse_code' => '11330213',
		  'id' => '2',
		  'username' => '0',
		);
		$owner_status=session('company.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if(!$owner_status){//不是货主（主erp）
			$this->is_owner($param['username'],$param['warehouse_code']);
		}
		if(empty($param['username'])){
			$username=session('company.username');
		}else{
			$username=$param['username'];
		}
		$id=$param['id'];
		$m=M('Pushordertest', C('DB_PREFIX_T'), C('db_config'));
		$map['id']=$id;	
		
		$url=C('base_config.order_del');
		$m_info=$m->where($map)->find();
		
		$order_no=$m_info['order_no'];
		$old_order_no=$m_info['old_order_no'];
		$push_status=$m_info['push_status'];
		
		if(empty($push_status) or ($m_info['oms_del']==1)){//未推送或者oms已删单
			//删除订单-自动回调库存-begin
			$g=M('Pushordergoods', C('DB_PREFIX_T'), C('db_config'));
			// $g_list=$g->field('goods_batch_no')->where(array('order_id'=>$id))->select();
			$g_list=$g->field('goods_batch_no,goods_price,goods_nums,goods_no')->where(array('order_id'=>$id))->select();
			
			if(empty($g_list)){
				echo "没有查到冻结库存数据";
				die;
			}
			// $api_url="http://es.jm.com/index.php?s=/Pushreceiveapi/release_storage";//测试释放库存接口
			// $api_url="http://www.t-cang.com/wmstest/index.php?s=/Pushreceiveapi/release_storage";//释放库存接口
			// $api_url_un="http://www.t-cang.com/oms/index.php/Api/ErpApi/unfreeze_money";//保证金扣费预估(释放金额)接口
			$push_data['g_list']=$g_list;
			$push_data['warehouse_code']=$param['warehouse_code'];
			$push_data['merchant_code']=C("base_config.merchant_code");
			$push_data['order_no']=$order_no;
			
			// $res_g=push($api_url,$push_data);
			// $res_g=json_decode($res_g,true);
			$res_g['status']=1;
			if(!$res_g['status']){
				echo $res_g['message'];
				die;
			}else{
				//税金计算-begin
				$total_price=0;
				$order_tax=0;
				$total_order_tax=0;
				foreach($g_list as $ks=>$vs){
					$order_tax=0;//订单总税金
					$goods_price=sprintf("%.2f",$vs['goods_price']*$vs['goods_nums']);//商品总价格=单价*数量
					$goods_info=M('Product', C('DB_PREFIX_T'), C('db_config'))->where(array('goods_no'=>$vs['goods_no']))->find();
					$ems_fee=$m_info['ems_fee'];//运费
					$insure_amount=0;//保费
					$consumption_rate=$goods_info['consumption_rate'];//消费税率
					$increment_rate=$goods_info['increment_rate'];//增值税率
					$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
					$total_price+=$goods_price;//总价格(不含税)
					$order_tax+=$goods_tax;//订单总税金
					$total_order_tax+=$goods_tax;//全部税金
				}
				//税金计算-end
				$api_push_data=array();
				$u_info=M('User')->where(array('username'=>$username))->find();
				$api_push_data['customer']['user_code']=$u_info['user_code'];
				$api_push_data['customer']['user_key']=$u_info['user_key'];
				$api_push_data['data']['order_tax']=$total_order_tax;
				//释放冻结金额-begin
				// if($order_no!='P2018081400601'){
					// $api_res_un=push($api_url_un,$api_push_data);
				// }else{
					// file_put_contents('./P2018081400601.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
				// }
				//释放冻结金额-end
			}
			//删除订单-自动回调库存-end
			$data['status'] = -1;
			$data['order_no']=$order_no."-bak";
			
			//原始订单号修改-begin
			$map_old=[];
			$map_old['old_order_no']=['like',"%$old_order_no%"];
			$old_del_no=$m->where($map_old)->order('id asc')->getField('old_order_no');

			$data['old_order_no']=$old_del_no."-bak";
			//原始订单号修改-end
			
			$status=$m->where($map)->save($data);
			if($status!==false){
				echo "y";
			}else{
				echo "删除成功";
			}
		}else{//已推送 走删单接口
			echo "已推送订单不能删除";
			exit;
		}
	}
	//更新总库存(奶粉周流程)
	//$goods_no 商品编码
	//$nums 数量
	//$add 增加 false减少
	public function edit_storagegoodsnums($goods_no,$nums,$add=true,$inbound=false){
		$g=M('Goods', C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . C('erp_dbname'));
		$map['goods_no']=$goods_no;
		$info=$g->where($map)->find();
		// dump($info);
		if(empty($info)){
			alert_json(0,'库存中没有查到对应商品');
		}
		if($add){
			if($inbound){//入库则总数量叠加
				$data['amount']=array('exp','amount+'.$nums);//总数量
			}
			$data['storage_amount']=array('exp','storage_amount+'.$nums);//剩余库存
		}else{
			if($info['storage_amount']-$nums<0){
				alert_json(0,'库存不足');
			}
			$data['storage_amount']=array('exp','storage_amount-'.$nums);//剩余库存
		}
		$res=$g->where($map)->save($data);
		if($res!==false){
			return 1;
		}else{
			// $trans->rollback();
			alert_json(0,'扣减库存出错');
		}
	}
}